<template>
  <div class="user-container">
    <div class="top-bg" />
    <h1><img src="@/assets/images/logo-white.png" alt="佰材网"><span>商户工作台</span></h1>
    <div class="box">
      <div class="box1">
        <div class="left">
          <el-carousel height="100%" arrow="never" :interval="4000">
            <el-carousel-item v-for="item in adList" :key="item.id" :style="{backgroundImage: 'url('+item.images+')', backgroundRepeat: 'no-repeat', backgroundSize: 'cover'}">
              <app-link class="learn-more" :to="resolvePath(item.linkUrl.toString())">
                了解更多
                <span class="svg-container"><svg-icon icon-class="circle-arrow-right" /></span>
              </app-link>
            </el-carousel-item>
          </el-carousel>
        </div>
        <div class="right">
          <el-form
            v-if="params === 'login'"
            ref="loginForm"
            :model="loginForm"
            :rules="loginRules"
            class="login-form"
            label-position="left"
          >
            <div class="title-container">
              <h3 class="title">账号登录</h3>
              <img class="avatar" src="@/assets/images/avatar.png">
            </div>

            <el-form-item prop="phone">
              <el-input
                ref="username"
                v-model.trim="loginForm.phone"
                placeholder="请输入用户名/手机号"
                name="phone"
                type="text"
                tabindex="1"
                autocomplete="on"
                size="mini"
                prefix-icon="el-icon-user"
              />
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                :key="passwordType"
                ref="password"
                v-model="loginForm.password"
                :type="passwordType"
                placeholder="请输入密码"
                name="password"
                tabindex="2"
                autocomplete="on"
                prefix-icon="el-icon-unlock"
                @keyup.enter.native="handleLogin"
              />
              <span class="show-pwd" @click="showPwd">
                <svg-icon
                  :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
                />
              </span>
            </el-form-item>

            <el-button
              round
              :loading="loading"
              type="primary"
              style="width:100%;margin-bottom:30px;"
              @click.native.prevent="handleLogin"
            >登 录</el-button>
            <div class="func">
              <router-link class="forgetPsd" to="/user/forget">忘记密码？</router-link>
              <router-link class="to-register" to="/user/register">立即注册</router-link>
            </div>
          </el-form>
          <!-- register -->
          <el-form
            v-if="params === 'register'"
            ref="registerForm"
            :model="registerForm"
            :rules="registerRules"
            class="login-form register-form"
            label-position="left"
          >
            <div class="title-container">
              <h3 class="title">免费注册</h3>
            </div>

            <el-form-item prop="phone">
              <el-input
                ref="phone"
                v-model.trim="registerForm.phone"
                placeholder="请输入手机号"
                name="phone"
                type="text"
                tabindex="1"
                autocomplete="on"
                size="mini"
                prefix-icon="el-icon-user"
              />
            </el-form-item>

            <el-form-item prop="isMan">
              <mousemove-validate @handle="validateMan" />
            </el-form-item>

            <el-form-item prop="verificationCode">
              <el-input
                ref="verificationCode"
                v-model.number="registerForm.verificationCode"
                type="text"
                placeholder="请输入短信验证码"
                name="verificationCode"
                tabindex="2"
              >
                <svg-icon slot="prefix" icon-class="icon-safe" class="el-input__icon" />
                <span slot="suffix" class="get-code" :style="{cursor: (registerForm.isMan ? 'pointer' : 'not-allowed')}" @click="getCode">获取短信验证码</span>
              </el-input>
            </el-form-item>

            <el-form-item prop="password1">
              <el-input
                :key="passwordType1"
                ref="password1"
                v-model="registerForm.password1"
                :type="passwordType1"
                placeholder="请输入密码"
                name="password1"
                tabindex="3"
                autocomplete="on"
                prefix-icon="el-icon-unlock"
              />
              <span class="show-pwd" @click="showPwd1">
                <svg-icon
                  :icon-class="passwordType1 === 'password' ? 'eye' : 'eye-open'"
                />
              </span>
            </el-form-item>

            <el-form-item class="check-password" prop="password2">
              <el-input
                :key="passwordType2"
                ref="password2"
                v-model="registerForm.password2"
                :type="passwordType2"
                placeholder="请再次输入密码"
                name="password"
                tabindex="4"
                autocomplete="on"
                prefix-icon="el-icon-unlock"
              />
              <span class="show-pwd" @click="showPwd2">
                <svg-icon
                  :icon-class="passwordType2 === 'password' ? 'eye' : 'eye-open'"
                />
              </span>
            </el-form-item>
            <el-form-item class="check-agree" prop="agree">
              <el-checkbox ref="agree" v-model="registerForm.agree" tabindex="5">我已同意并阅读</el-checkbox> <span class="treaty">《佰材网商家注册协议》</span>
            </el-form-item>
            <el-button
              class="register-btn"
              round
              :loading="loading"
              type="primary"
              style="width:100%;margin-bottom:30px;"
              :disabled="!registerForm.agree"
              @click.native.prevent="handleRegister"
            >注 册</el-button>
            <div class="func">
              <router-link class="to-register" to="/user/login?redirect=home">已有账号？马上登陆</router-link>
            </div>
          </el-form>
          <!-- forget password -->
          <el-form
            v-if="params === 'forget'"
            ref="registerForm"
            :model="forgetForm"
            :rules="forgetRules"
            class="login-form register-form"
            label-position="left"
          >
            <div class="title-container">
              <h3 class="title">忘记密码</h3>
            </div>

            <el-form-item prop="phone">
              <el-input
                ref="phone"
                v-model.trim="forgetForm.phone"
                placeholder="请输入手机号"
                name="phone"
                type="text"
                tabindex="1"
                autocomplete="on"
                size="mini"
                prefix-icon="el-icon-user"
              />
            </el-form-item>

            <el-form-item prop="isMan">
              <mousemove-validate @handle="validateMan2" />
            </el-form-item>

            <el-form-item prop="verificationCode">
              <el-input
                ref="verificationCode"
                v-model.number="forgetForm.verificationCode"
                type="text"
                placeholder="请输入短信验证码"
                name="verificationCode"
                tabindex="2"
              >
                <svg-icon slot="prefix" icon-class="icon-safe" class="el-input__icon" />
                <span slot="suffix" class="get-code" :style="{cursor: (forgetForm.isMan ? 'pointer' : 'not-allowed')}" @click="getCode2">获取短信验证码</span>
              </el-input>
            </el-form-item>

            <el-form-item prop="password3">
              <el-input
                :key="passwordType3"
                ref="password1"
                v-model="forgetForm.password3"
                :type="passwordType3"
                placeholder="请设置新的登陆密码"
                name="password1"
                tabindex="3"
                autocomplete="on"
                prefix-icon="el-icon-unlock"
              />
              <span class="show-pwd" @click="showPwd3">
                <svg-icon
                  :icon-class="passwordType3 === 'password' ? 'eye' : 'eye-open'"
                />
              </span>
            </el-form-item>

            <el-form-item class="check-password" prop="password4">
              <el-input
                :key="passwordType4"
                ref="password4"
                v-model="forgetForm.password4"
                :type="passwordType4"
                placeholder="请再次输入新的登陆密码"
                name="password"
                tabindex="4"
                autocomplete="on"
                prefix-icon="el-icon-unlock"
              />
              <span class="show-pwd" @click="showPwd4">
                <svg-icon
                  :icon-class="passwordType4 === 'password' ? 'eye' : 'eye-open'"
                />
              </span>
            </el-form-item>
            <el-button
              class="register-btn"
              round
              :loading="loading"
              type="primary"
              style="width:100%;margin-bottom:30px;"
              @click.native.prevent="handleForget"
            >确 认</el-button>
            <div class="func">
              <router-link class="to-register" to="/user/login?redirect=home">已想起密码？马上登录</router-link>
            </div>
          </el-form>
        </div>
      </div>
    </div>
    <p class="copyright">CopyRight © 2018-<span>{{ new Date().getFullYear() }}</span> 北京佰材天下电子商务有限公司 All Rights Reserved 版权所有</p>
  </div>
</template>

<script>
import { validUsername, validPhone, validPassword, validPureNum, isExternal } from '@/utils/validate';
import MousemoveValidate from './components/MousemoveValidate';
import { getLoginAd } from '@/api/statistics';
import AppLink from '@/layout/components/Sidebar/Link';
import path from 'path';
export default {
  name: 'User',
  components: { MousemoveValidate, AppLink },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value.length === 11 && validPureNum(value)) {
        if (!validPhone(value)) {
          callback(new Error('请输入正确的手机号'));
        } else {
          callback();
        }
      } else {
        if (!validUsername(value)) {
          callback(new Error('请输入正确的用户名'));
        } else {
          callback();
        }
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6 || value.length > 20) {
        callback(new Error('密码长度在6到20个数之间'));
      } else if (!validPassword(value)) {
        callback(new Error('密码中必须包含字母(不区分大小写)、数字'));
      } else {
        callback();
      }
    };
    const validatePhoneNum = (rule, value, callback) => {
      if (!validPhone(value)) {
        callback(new Error('请输入正确的手机号码'));
      } else {
        callback();
      }
    };
    const validateVerCode = (rule, value, callback) => {
      if (!validPureNum(value) || value.toString().length !== 6) {
        callback(new Error('请输入正确的手机验证码'));
      } else {
        callback();
      }
    };
    const validatePassword2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.registerForm.password1) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    const validateAgree = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请先阅读注册协议并同意'));
      } else {
        callback();
      }
    };
    return {
      basePath: '',
      adList: [],
      loginForm: {
        phone: '',
        password: ''
      },
      registerForm: {
        phone: '',
        verificationCode: null,
        password1: '',
        password2: '',
        agree: false,
        isMan: false
      },
      forgetForm: {
        phone: '',
        verificationCode: null,
        password3: '',
        password4: '',
        isMan: false
      },
      loginRules: {
        username: [
          { required: true, trigger: 'blur', validator: validateUsername }
        ],
        password: [
          { required: true, trigger: 'blur', validator: validatePassword }
        ]
      },
      registerRules: {
        phone: [
          { required: true, trigger: 'blur', validator: validatePhoneNum }
        ],
        verificationCode: [
          { required: true, trigger: 'blur', validator: validateVerCode }
        ],
        password1: [
          { required: true, trigger: 'blur', validator: validatePassword }
        ],
        password2: [
          { required: true, trigger: 'blur', validator: validatePassword2 }
        ],
        agree: [
          { required: true, trigger: 'blur', validator: validateAgree }
        ]
      },
      forgetRules: {
        phone: [
          { required: true, trigger: 'blur', validator: validatePhoneNum }
        ],
        verificationCode: [
          { required: true, trigger: 'blur', validator: validateVerCode }
        ],
        password3: [
          { required: true, trigger: 'blur', validator: validatePassword }
        ],
        password4: [
          { required: true, trigger: 'blur', validator: validatePassword2 }
        ]
      },
      loading: false,
      passwordType: 'password',
      passwordType1: 'password',
      passwordType2: 'password',
      passwordType3: 'password',
      passwordType4: 'password',
      redirect: undefined,
      params: ''
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        const redirect = route.query && route.query.redirect;
        this.redirect = redirect && redirect.indexOf('register') > -1 ? 'home' : redirect;
        this.params = route.params && route.params.type;
      },
      immediate: true
    }
  },
  created() {
    this.getLoginAd();
  },
  methods: {
    getLoginAd() {
      new Promise((resolve, reject) => {
        getLoginAd({}).then(({ data }) => {
          this.adList = data;
          resolve(data);
        }).catch(err => {
          reject(err);
        });
      });
    },
    validateMan(isMan) {
      this.registerForm.isMan = isMan;
    },
    validateMan2(isMan) {
      this.forgetForm.isMan = isMan;
    },
    getCode() {
      if (this.registerForm.isMan) return;
    },
    getCode2() {
      if (this.forgetForm.isMan) return;
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = '';
      } else {
        this.passwordType = 'password';
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    showPwd1() {
      if (this.passwordType1 === 'password') {
        this.passwordType1 = '';
      } else {
        this.passwordType1 = 'password';
      }
      this.$nextTick(() => {
        this.$refs.password1.focus();
      });
    },
    showPwd2() {
      if (this.passwordType2 === 'password') {
        this.passwordType2 = '';
      } else {
        this.passwordType2 = 'password';
      }
      this.$nextTick(() => {
        this.$refs.password2.focus();
      });
    },
    showPwd3() {
      if (this.passwordType3 === 'password') {
        this.passwordType3 = '';
      } else {
        this.passwordType3 = 'password';
      }
      this.$nextTick(() => {
        this.$refs.password3.focus();
      });
    },
    showPwd4() {
      if (this.passwordType4 === 'password') {
        this.passwordType4 = '';
      } else {
        this.passwordType4 = 'password';
      }
      this.$nextTick(() => {
        this.$refs.password4.focus();
      });
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch('login', this.loginForm)
            .then(() => {
              this.loading = false;
              this.$message({
                message: '登录成功！',
                type: 'success',
                duration: 1000
              });
              const { search } = window.location;
              if (search) {
                this.$router.go(-1);
              } else {
                this.$router.push({ path: '/' });
              }
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    handleRegister() {
      this.$refs.registerForm.validate(valid => {
        const { phone } = this.registerForm;
        const password = this.registerForm.password1;
        const code = this.registerForm.verificationCode;
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch('register', {
              phone,
              code,
              password,
              logo: 'web/public/init-logo.png',
              avatar: 'web/public/avatar.png',
              mainimage: 'web/public/init-main-pic.png'
            }).then(() => {
              this.loading = false;
              this.$message({
                message: '恭喜你，注册成功！',
                type: 'success',
                duration: 1000,
                onClose: () => {
                  this.$router.push({ path: this.redirect || '/' });
                }
              });
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    handleForget() {
      this.$refs.forgetForm.validate(valid => {
        const { phone } = this.forgetForm;
        const password = this.forgetForm.password3;
        const code = this.forgetForm.verificationCode;
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch('forgetPassword', { phone, code, password }).then(() => {
              this.loading = false;
              this.$message({
                message: '密码修改成功！',
                type: 'success',
                duration: 1000,
                onClose: () => {
                  this.$router.push({ path: this.redirect || '/' });
                }
              });
            }).catch(() => {
              this.loading = false;
            });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resolvePath(routePath) {
      if (isExternal(routePath)) {
        return routePath;
      }
      if (isExternal(this.basePath)) {
        return this.basePath;
      }
      return path.resolve(this.basePath, routePath);
    }
  }
};
</script>

<style lang="scss">

/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #fff;
$cursor: #838a9d;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .user-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.user-container {
  .el-carousel {
    height: 100%;
  }
  .el-input {
    height: 100%;
    input {
      background: transparent;
      -webkit-appearance: none;
      border-radius: 0px;
      color: $textColorBase;
      height: 40px;
      border-radius: 20px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    height: 40px;
    width: 100%;
    background: #fff;
    color: $textColorBase;
    margin-bottom: 30px;
    box-sizing: border-box;
    &.check-password{
      margin-bottom: 20px;
    }
    &.check-agree{
      height: 24px;
      margin-bottom: 10px;
      .el-form-item__content{
        line-height: 24px;
        text-align: center;
      }
    }
  }
  .el-form-item__error{
    padding-left: 15px;
  }
  .el-input__icon{
    font-size: 18px;
    color: $mainColor;
  }
  .el-input--prefix .el-input__inner{
    padding-left: 35px;
  }
  .el-checkbox{
    color: $textColorBase;
    &:focus{
      outline: none;
    }
  }
  .el-checkbox__input.is-checked+.el-checkbox__label{
    color: $textColorBase
  }
}
</style>

<style lang="scss" scoped>
$bg: #0A2140;
$dark_gray: #889aa4;

.top-bg{
  width: 100%;
  height: 50vh;
  background: url('../../assets/images/user-bg.png') no-repeat center top;
  background-size: cover;
}
.box{
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100vh;
  position: absolute;
  left: 0;
  top: 0;
  z-index: 2;
}
.box1{
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;
  width: 70vw;
  height: 80vh;
  max-width: 970px;
  max-height: 590px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  .left,.right{
    height: 100%;
    overflow: hidden;
    box-sizing: border-box
  }
  .left{
    width: 51%;
    flex: 0 0 51%;
    border-top-left-radius: 8px;
    border-bottom-left-radius: 8px;
  }
  .right{
    width: 49%;
    flex: 0 0 49%;
    padding: 0 8%;
  }
}
.user-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  position: relative;
  color: #fff;
  h1{
    width: 100%;
    text-align: center;
    font-size: 34px;
    vertical-align: middle;
    position: absolute;
    left: 0;
    top: 2vh;
    img,span{
      vertical-align: middle;
      display: inline-block;
    }
    span{
      border-left: 2px solid #fff;
      padding-left: 30px;
      margin-left: 30px
    }
  }
  .login-form {
    position: relative;
    width: 100%;
    max-width: 100%;
    margin: 0 auto;
    overflow: hidden;
  }
  .register-form{
    .svg-icon{
      vertical-align: -0.35em;
      padding-left: 3px;
    }
    .title-container {
      margin-bottom: 10%;
    }
  }
  .svg-container {
    padding: 0 5px 0 15px;
    color: $mainColor;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;
    text-align: center;
    padding-top: 15%;
    margin-bottom: 15%;
    .title {
      font-size: $fontSizeXXBig;
      color: $mainColor;;
      margin: 0px auto 25px auto;
      text-align: center;
      font-weight: bold;
      line-height: 1.2;
    }
    .avatar{
      display: inline-block;
      width: 100px;
      height: 100px;
      border-radius: 50%
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 0;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
  .copyright{
    width: 100%;
    text-align: center;
    position: absolute;
    left: 0;
    bottom: 2vh;
  }
}

.left{
  position: relative;
  .learn-more{
    color: #fff;
    position: absolute;
    text-align: center;
    left: 0;
    bottom: 10%;
    width: 100%;
    font-size: 14px;
    line-height: 1.5;
    .svg-container{
      width: auto;
      padding: 0 0 2px 5px;
    }
  }
  .el-carousel__item:nth-child(2n) {
     background-color: #99a9bf;
  }
  .el-carousel__item:nth-child(2n+1) {
     background-color: #d3dce6;
  }
}
.func{
  text-align: center;
  .forgetPsd,
  .to-register{
    font-size: $fontSizeBase;
    line-height: 1.2
  }
  .forgetPsd{
    color: #999;
    border-right: 2px solid $borderColor;
    padding-right: 8px;
    margin-right: 8px;
  }
  .to-register{
    color: $mainColor
  }
}
.get-code,.treaty{
  color: $mainColor;
  cursor: pointer;
}
.register-btn{
  margin-bottom: 15px !important;
}
</style>
